package second.backtracking;

import java.util.ArrayList;
import java.util.List;

public class Solution04 {
    List<List<Integer>> res;
    List<Integer> tmp;

    int sum;

    public List<List<Integer>> combinationSum3(int k, int n) {
        res = new ArrayList<>();
        tmp = new ArrayList<>();
        back(1, k, n);
        return res;
    }

    public void back(int index, int k, int n) {
        if (tmp.size() == k) {
            if (sum == n) {
                res.add(new ArrayList<>(tmp));
                return;
            }
        }
        if (sum >= n) return;
        for (int i = index; i <= 9; i++) {
            tmp.add(i);
            sum += i;
            back(i + 1, k, n);
            sum -= i;
            tmp.remove(tmp.size() - 1);
        }
    }
}
